# coding:utf-8

import os
import urllib
import set_env_path     # 请勿删除


from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from common.wechat_util import send_template_message, grequest_send

Base = declarative_base()
engine = create_engine(
    os.getenv('DATABASE_URL')
    or 'mysql+pymysql://root:@127.0.0.1/wph_www_prod?charset=utf8'
)
Session = sessionmaker(bind=engine)
session = Session()


def fix_send_wx_notify():
    """
    created by chenhj at 2017/8/21
    补发2017-8-01 ~ 2017-8-18期间到期的用户提醒
    因为当时定时任务有问题, 导致发送失败
    """
    def gen_message(user, template_id, url):
        """
        created by chenhj at 2017/8/2

        """
        return {
            'openid': user.openid,
            'template_id': template_id,
            'data': {
                "first": {
                    "value": "您的套餐增值服务已经到期，我们将停止为您推送新项目订单，您也将无法拨打客户电话。\n",
                    "color": "#173177"
                },
                "keyword1": {
                    "value": "万屏汇",
                    "color": "#173177"
                },
                "keyword2": {
                    "value": "增值套餐",
                    "color": "#173177"
                },
                "keyword3": {
                    "value": user.end_date.strftime('%F'),
                    "color": "#173177"
                },
                "remark": {
                    "value": "\n速戳进行续费↓↓↓",
                    "color": "#4785F9"
                }
            },
            'url': url
        }

    select_wx_user_sql = """
        select distinct wx_openid as openid, pack.end_date from user join pack
        on user.id = pack.uid
        where wx_openid != '' and pack.end_date <= '2017-08-18'
          and pack.end_date >= '2017-08-01' and pack.deleted_at=0
    """
    select_wx_template_sql = """
        select template_code from wechat_template where code='pack_end'
    """

    domain = os.environ.get('wph_host') or ''
    url = urllib.parse.urljoin(domain, 'user/valueaddservice.html')
    result = session.execute(select_wx_user_sql).fetchall()
    wx_template = session.execute(select_wx_template_sql).fetchone()
    template_id = wx_template.template_code

    req_set = set()
    for each in result:
        req_set.add(send_template_message(**gen_message(each, template_id, url)))
        if len(req_set) == 100:
            grequest_send(req_set)
            req_set.clear()
    if req_set:
        grequest_send(req_set)

    session.commit()
    session.close()

if __name__ == '__main__':
    fix_send_wx_notify()
